package Concurrency2.Chapter02_InnerLockPrinciple.P04_FatLock;

import org.openjdk.jol.info.ClassLayout;

import java.util.concurrent.CountDownLatch;

/**
 * 重量级锁: 锁对象的状态查看
 */
public class FatLock2 {
    public static void main(String[] args) {
        SomeLock someLock = new SomeLock();
        CountDownLatch countDownLatch = new CountDownLatch(2);
        printLockObject(someLock, "重量级锁获取之前的锁状态");

        Runnable task = () -> {
            synchronized (someLock) {
                System.out.println("ThreadID: " + Thread.currentThread().getId() + " 执行完成");
                printLockObject(someLock, "执行过程中的锁状态");
                countDownLatch.countDown();
            }
        };
        Thread t1 = new Thread(task, "T1");
        Thread t2 = new Thread(task, "T2");
        t1.start();
        t2.start();
        // 让t1与t2都顺利执行完成
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        printLockObject(someLock, "重量级锁释放之后的锁状态");
        System.out.println("==================================================================================");
        //下面再次开启一个线程获取锁, 查看锁的状态是否为重量级锁, 即验证锁的升级过程是否可以回退
        Thread t3 = new Thread(task, "T3");
        t3.start();
        try {
            t3.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        printLockObject(someLock, "重量级锁释放之后的锁状态");
    }

    private static void printLockObject(Object object, String message) {
        String lockObject = ClassLayout.parseInstance(object).toPrintable();
        System.out.println(message + ": \n" + lockObject);
    }

    static class SomeLock {
    }
}
